//
//  WXPAuthBankCardVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/27.
//
//

#import "WXPAuthBankCardVC.h"
#import "WXPAuthBankCardHeaderView.h"
#import "WXPAuthBankCardFooterView.h"
#import "WXPAuthSelectView.h"
#import "WXPAutoFirstBorrowPopUpView.h"
#import "WXPSubmitOrderSuccessVC.h"

@interface WXPAuthBankCardVC ()<UITextFieldDelegate>

@property (nonatomic, strong) WXPAuthBankCardHeaderView * viewHeader;
@property (nonatomic, strong) UIView * viewBankCardTips;
@property (nonatomic, strong) UIView * viewVerifyBankCard;
@property (nonatomic, strong) WXPAuthSelectView * tfVerifyBankCard;
@property (nonatomic, strong) WXPAuthBankCardFooterView * viewFooter;
@property (nonatomic, strong) WXPAutoFirstBorrowPopUpView * autoFirstBorrowPopUpView;

@property (nonatomic, assign) BOOL bankCardSuccess;
@property (nonatomic, assign) BOOL verifyBankCardSuccess;

@end

@implementation WXPAuthBankCardVC

#pragma mark - lazy
- (WXPAuthBankCardHeaderView *)viewHeader{
    if (!_viewHeader) {
        _viewHeader = [WXPAuthBankCardHeaderView new];
        _viewHeader.type = 1;
        WEAKSELF
        _viewHeader.tfBankCard.blockTextFieldDidChange = ^{
            [weakSelf verifyBankCard];
            [weakSelf verifyConfirmarBankCard];
        };
        _viewHeader.blockResetAuthBtn = ^{
            [weakSelf resetAuthBtn];
        };
    }
    return _viewHeader;
}
- (UIView *)viewBankCardTips
{
    if (_viewBankCardTips == nil) {
        _viewBankCardTips = [UIView  new];
        _viewBankCardTips.widthHeight = XY(SCREEN_WIDTH, 0);
        _viewBankCardTips.backgroundColor = [UIColor clearColor];
        UIView * view = [UIView new];
        view.backgroundColor = COLOR_WHITE;
        view.width = SCREEN_WIDTH-2*LEFT_MARDIN;
        [_viewBankCardTips addSubview:view];
        UILabel * titleLabel = [UILabel new];
        titleLabel.fontNum = 12;
        titleLabel.textColor = COLOR_RED;
        titleLabel.numberOfLines = 0;
        titleLabel.lineSpace = 3;
        [titleLabel fitTitle:@"Por favor, ingrese su número CLABE INTERBANCARIA tal como aparece en su Estado de Cuenta, asegurándose de que conste de 18 dígitos. O proporcione su número de tarjeta bancaria tal como aparece en su tarjeta, asegurándose de que conste de 16 dígitos" variable:SCREEN_WIDTH-4*LEFT_MARDIN];
        titleLabel.leftTop = XY(LEFT_MARDIN, Ratio(12));
        [view addSubview:titleLabel];
        view.height = titleLabel.bottom;
        view.centerXTop = XY(SCREEN_WIDTH/2, 0);
        _viewBankCardTips.height = view.bottom;
    }
    return  _viewBankCardTips;
}
// 确认银行卡号
- (UIView *)viewVerifyBankCard{
    if (!_viewVerifyBankCard) {
        _viewVerifyBankCard = [UIView new];
        _viewVerifyBankCard.width = SCREEN_WIDTH;
        UIView * view = [UIView new];
        view.backgroundColor = COLOR_WHITE;
        view.width = SCREEN_WIDTH-2*LEFT_MARDIN;
        [_viewVerifyBankCard addSubview:view];
        [view addSubview:self.tfVerifyBankCard];
        self.tfVerifyBankCard.centerXTop = XY(view.width/2, 0);
        view.height = self.tfVerifyBankCard.bottom;
        view.centerXTop = XY(_viewVerifyBankCard.width/2, 0);
        _viewVerifyBankCard.height = view.bottom;
    }
    return _viewVerifyBankCard;
}
- (WXPAuthSelectView *)tfVerifyBankCard
{
    if (_tfVerifyBankCard == nil) {
        _tfVerifyBankCard = [WXPAuthSelectView  new];
        _tfVerifyBankCard.tag = 1;
        _tfVerifyBankCard.tfContent.keyboardType = UIKeyboardTypeNumberPad;
        _tfVerifyBankCard.tfContent.font = [UIFont systemFontOfSize:14];
        _tfVerifyBankCard.imageArrow.hidden = true;
        _tfVerifyBankCard.tfContent.userInteractionEnabled = true;
        ModelBtn * model = [ModelBtn new];
        model.title = @"Verificar la cuenta CLABE o tarjeta bancaria";
        model.content = @"Por favor escribe";
        [_tfVerifyBankCard resetViewWithModel:model];
        _tfVerifyBankCard.tfContent.delegate = self;
        WEAKSELF
        _tfVerifyBankCard.blockTextFieldDidChange = ^{
            [weakSelf verifyBankCard];
            [weakSelf verifyConfirmarBankCard];
        };
        //        _tfVerifyBankCard.blockTextFieldDidChange = ^(BOOL isInput) {
        //            [weakSelf verifyBankCard];
        //            [weakSelf verifyConfirmarBankCard];
        //
        //            // 这个类里面两个LRBMailTextField，没法直接用isInput区分了
        ////            if(isInput){
        ////                [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_INPUT type:KEY_input];
        ////            }
        //            // 区分是输入
        //            static NSUInteger previousLength = 0;
        //            NSUInteger currentLength = weakSelf.tfVerifyBankCard.contentTextField.text.length;
        ////            if (currentLength > previousLength || isInput) {
        //            if (isInput) {
        //                [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_INPUT type:KEY_input];
        //            }
        //            previousLength = currentLength;
        //
        //
        //
        //            [weakSelf.tfVerifyBankCard.contentTextField becomeFirstResponder];
        //        };
                
        //        _tfVerifyBankCard.blockTextFieldDidEndEditing = ^{
        //            [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_LOST_FOCUS type:KEY_input];
        //        };
        //        _tfVerifyBankCard.blockCharactersInRange = ^{
        //            [GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_PARSE type:KEY_input];
        //        };
    }
    return  _tfVerifyBankCard;
}
- (WXPAuthBankCardFooterView *)viewFooter{
    if (!_viewFooter) {
        _viewFooter = [WXPAuthBankCardFooterView new];
    }
    return _viewFooter;
}
- (WXPAutoFirstBorrowPopUpView *)autoFirstBorrowPopUpView{
    if (!_autoFirstBorrowPopUpView) {
        _autoFirstBorrowPopUpView = [WXPAutoFirstBorrowPopUpView new];
    }
    return _autoFirstBorrowPopUpView;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyBankcard featureName:KEY_Page action:KEY_ENTER type:KEY_page];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyBankcard featureName:KEY_Page action:KEY_OUT type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyBankcard action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    self.bankCardSuccess = true;
    self.verifyBankCardSuccess = true;
    
    [self.navView resetViewWithTitle:@"Vincular cuenta bancaria CLABE"];
    self.progressView.numLabel.hidden = true;
    [self.progressView.moneyView resetViewWithTag:6];
    [self resetHeaderView];
    [self resetFooterView];
    WEAKSELF
    [self.btnAuth setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
        [NSObject clickFeedback];
        [weakSelf.btnAuth addClickAnimate];
        [weakSelf requestSubmitAuth];
    }];
    
    [self requestBankList];
    [self requestShowAutoFirstLoan];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.progressView,
        [GlobalMethod getViewWithHeight:16],
        self.viewHeader,
    ]];
    self.tableView.tableHeaderView = self.headerView;
}

- (void)resetFooterView{
    [self.viewFooter resetVerifyBankCardIsShowTips:!self.verifyBankCardSuccess];
    UIView * view = [UIView initWithViews:@[
        self.viewFooter,
        [GlobalMethod getViewWithHeight:LEFT_MARDIN],
    ]];
    self.tableView.tableFooterView = view;
}

// 验证 银行卡号
- (void)verifyBankCard{
    BOOL change = false;
    BOOL result = (self.viewHeader.tfBankCard.tfContent.text.length == 16 || self.viewHeader.tfBankCard.tfContent.text.length == 18);
    result = isStr(self.viewHeader.tfBankCard.tfContent.text)?result:true;
    change = self.bankCardSuccess==result?false:true;
    self.bankCardSuccess = result;
    if(change){
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
// 验证 确认银行卡号
- (void)verifyConfirmarBankCard{
    BOOL change = false;
    BOOL result = (self.tfVerifyBankCard.tfContent.text.length == 16 || self.tfVerifyBankCard.tfContent.text.length == 18);
    result = ([self.viewHeader.tfBankCard.tfContent.text isEqualToString:self.tfVerifyBankCard.tfContent.text])?true:false;
    result = isStr(self.tfVerifyBankCard.tfContent.text)?result:true;
    change = self.verifyBankCardSuccess==result?false:true;
    self.verifyBankCardSuccess = result;
    if(change){
        [self resetFooterView];
    }
     [self resetAuthBtn];
}

// 认证按钮更新
- (void)resetAuthBtn{
    if(self.bankCardSuccess &&
       self.verifyBankCardSuccess &&
       isStr(self.viewHeader.tfBankCard.tfContent.text) &&
       isStr(self.tfVerifyBankCard.tfContent.text) &&
       isStr(self.viewHeader.bankNameView.tfContent.text)){
        self.btnAuth.userInteractionEnabled = true;
        self.btnAuth.alpha = 1;
    }else{
        self.btnAuth.userInteractionEnabled = false;
        self.btnAuth.alpha = 0.5;
    }
}

#pragma mark -  键盘
// 键盘收起时执行操作
- (void)keyboardWillHide:(NSNotification *)notification {
    self.viewHeader.pickerView.bottom = SCREEN_HEIGHT;
}
- (void)keyboardWillShow:(NSNotification *)notification {
    self.viewHeader.pickerView.bottom = SCREEN_HEIGHT-self.viewHeader.pickerView.viewBack.height+Ratio(26);
}
// 获得焦点
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [GlobalMethod hitPointWithPageName:KEY_VerifyBankcard action:KEY_CLABE2_Focus extInfo:nil];
    [GlobalMethod buryPointWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_GET_FOCUS type:KEY_input];
}
// 失去焦点
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [GlobalMethod buryPointWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_LOST_FOCUS type:KEY_input];
}

// 粘贴行为
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (isStr(string)) {
        [GlobalMethod buryPointWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_INPUT type:KEY_input];
    }
    // 检测是否为粘贴行为
    NSString * trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([UIPasteboard generalPasteboard].string.length > 0 && [trimmedString isEqualToString:[UIPasteboard generalPasteboard].string]) {
        [GlobalMethod buryPointWithPageName:KEY_VerifyBankcard featureName:KEY_Bank_Card_Input2 action:KEY_PARSE type:KEY_input];
        return true;
    }
    return YES;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        // 银行卡号错误提示
        return self.bankCardSuccess?[UIView new]:self.viewBankCardTips;
    }else{
        // 验证银行卡号
        return self.viewVerifyBankCard;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return self.bankCardSuccess?CGFLOAT_MIN:self.viewBankCardTips.height;
    }else{
        return self.viewVerifyBankCard.height;
    }
}
//table footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

#pragma mark - requeest
// 是否显示自动首借
- (void)requestShowAutoFirstLoan{
    [RequestApi requestShowAutoFirstLoanPopWindowWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        if ([response isKindOfClass:[NSNumber class]]) {
            if([(NSNumber *)response boolValue]){
                UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
                [window addSubview:self.autoFirstBorrowPopUpView];
            }
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 银行列表
- (void)requestBankList{
    [RequestApi requestBankListWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewHeader.bankNameAry = [response arrayValueForKey:KEY_banks];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
- (void)requestSubmitAuth{
    [GlobalMethod hitPointWithPageName:KEY_VerifyBankcard action:KEY_Save_Start extInfo:nil];
    NSDictionary * dic = @{
        KEY_bankCode: readStr(self.viewHeader.bankCode),
        KEY_bankName: readStr(self.viewHeader.bankNameView.tfContent.text),
        KEY_bankCard: readStr(self.tfVerifyBankCard.tfContent.text)
    };
    [RequestApi requestSaveUserInfoAuthBankCardWithData:dic step:KEY_BANK_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        if ([response isKindOfClass:[NSNumber class]]) {
            if([(NSNumber *)response boolValue] == true){
                // 打点 - 借款成功
                [GlobalMethod hitPointWithPageName:KEY_Products action:KEY_Apply_Loan_Success extInfo:nil];
                // 风控埋点
                [GlobalMethod addRiskControlWithType:KEY_BEGIN_LOAN startTime:[GlobalMethod getTimeStampMillisecond] endTime:[GlobalMethod getTimeStampMillisecond]];
                [GlobalMethod addRiskControlWithType:KEY_END_LOAN startTime:[GlobalMethod getTimeStampMillisecond] endTime:[GlobalMethod getTimeStampMillisecond]];
                
                // 跳转到订单提交成功页，并且需要展示订单提交成功页面的评价弹窗
                WXPSubmitOrderSuccessVC * vc = [WXPSubmitOrderSuccessVC new];
                vc.isShowScoreView = true;
                [Global_Nav pushViewController:vc animated:true];
            }else{
                [self.view endEditing:true];
                // 下一步
                [self requestGetNextStep];
            }
        }
        
        [GlobalMethod hitPointWithPageName:KEY_VerifyBankcard action:KEY_Save_End extInfo:nil];
        // 风控
        [GlobalMethod addRiskControlWithType:KEY_BANK startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

@end
